package com.shuyuntu.proposal.controller;

import com.shuyuntu.proposal.security.UseSecurity;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.PrintWriter;
import java.util.List;
import java.util.UUID;

/**
 * 解决图片上传的类
 * Created by limeng on 16/6/24.
 */
@Controller
@RequestMapping("/uploadImages")
public class UploadImageController {
    /**
     * 上传图片
     * @param request 请求
     * @param response 相应
     * @param session injection
     */
    @RequestMapping("/")
    @UseSecurity(category = "0100")
    public void doPost(HttpServletRequest request, HttpServletResponse response,
                       HttpSession session) {
        String path = request.getRealPath("/uploadImages");
        File file = new File(path);
        if (!file.exists())
            file.mkdirs();
        String fileName = "";// 文件名称

        /**上传文件处理内容**/
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload sfu = new ServletFileUpload(factory);
        sfu.setHeaderEncoding("UTF-8"); // 处理中文问题
        sfu.setSizeMax(1024 * 1024); // 限制文件大小
        try {
            List<FileItem> fileItems = sfu.parseRequest(request); // 解码请求
            for (FileItem fi : fileItems) {
                fileName = UUID.randomUUID()+fi.getName().substring(fi.getName().lastIndexOf("."),fi.getName().length());
                fi.write(new File(path, fileName));
            }
            //获取图片url地址
            String imgUrl = "http://localhost:8080/uploadImages/" + fileName;
            response.setContentType("text/text;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.print(imgUrl);  //返回url地址
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
